<!-- 后端账户信息 -->
<template>
  <div class="table">
    <!-- 列表 -->
    <SearchTable :selectOrganization="selectOrganization" :selectRole="selectRole" v-model:formStatus="formStatus" @handleViewEdit="handleViewEdit" ref="searchTableRef" />
    <!-- 弹窗表单 -->
    <FormDialog :selectOrganization="selectOrganization" :selectRole="selectRole" :userTags="userTags" v-model:formStatus="formStatus" v-model:form="userForm" @handleSuccess="handleSuccess" />
  </div>
</template>

<script setup lang="ts" name="userInfo">
import SearchTable from "@/components/user/userInfo/SearchTable.vue";
import FormDialog from "@/components/user/userInfo/FormDialog.vue";
import { getOrganizationInfo } from "@/utils/api/organization";
import { getRoleInfo } from "@/utils/api/role";
import type { IOrganization } from "@/types/organization";
import type { IMaster, IMasterList } from "@/types/master";
import type { IRole } from "@/types/role";
import type { ViewMode, ViewModeFilter } from "@/types/common";
import { useDictData } from "@/hooks/network/useDictData";
import type { IDictData } from "@/types/dict";
let { getDictData } = useDictData();
/*  */
const formStatus = ref<ViewMode>("none");
/* 组织 */
const selectOrganization = ref<Array<IOrganization>>([]);
/* 角色 */
const selectRole = ref<Array<IRole>>([]);
/* 标签 */
const userTags = ref<Array<IDictData>>([]);
/* 表格子组件的引用 */
const searchTableRef = useTemplateRef("searchTableRef");

/* 表单数据 */
const userForm = reactive<IMaster>({
  id: 0,
  agency_id: "",
  mobile: "",
  nick_name: "",
  role_id: "",
  user_name: "",
  avatar: "",
  tags: []
});

/* 请求：获取组织数据 */
function handleGetOrganizationInfo() {
  getOrganizationInfo<Array<IOrganization>>()
    .then(res => {
      selectOrganization.value = res.result;
    })
    .catch(() => {});
}
/* 请求：获取角色数据 */
function handleGetRoleInfo() {
  getRoleInfo<Array<IRole>, unknown>()
    .then(res => {
      selectRole.value = res.result;
    })
    .catch(() => {});
}

/* 点击编辑按钮 */
function handleViewEdit(row: IMasterList, code: ViewModeFilter) {
  formStatus.value = code;
  /* nextTick 解决重置该表单项 初始化的数据问题 */
  nextTick(() => {
    userForm.id = row.id;
    userForm.user_name = row.user_name;
    userForm.nick_name = row.nick_name;
    userForm.role_id = row.role_id;
    userForm.agency_id = row.agency_id;
    userForm.mobile = row.mobile;
    userForm.avatar = row.avatar;
    userForm.tags = row.masterTags.map(item => item.tag);
  });
}

/* 成功保存或者编辑的回调 */
function handleSuccess() {
  searchTableRef.value?.getTableInfo();
}

handleGetOrganizationInfo();
handleGetRoleInfo();
getDictData("USER_TAG", userTags);
</script>

<style lang="scss" scoped></style>
